#include "stdafx.h"
#include "FormUrlEncodedRequest.h"

FormUrlEncodedRequest::FormUrlEncodedRequest()
{
}

FormUrlEncodedRequest& FormUrlEncodedRequest::AddKeyValue(const char* key, const char* value)
{
	char szEncodedURL[ATL_URL_MAX_URL_LENGTH];
	ZeroMemory(szEncodedURL, sizeof(szEncodedURL));

	DWORD dwEncodedFileLength = 0;
	AtlEscapeUrl(value, szEncodedURL, &dwEncodedFileLength, ATL_URL_MAX_PATH_LENGTH-1);

	if (!m_content.IsEmpty())
		m_content += "&";

	m_content += key;
	m_content += "=";
	m_content += szEncodedURL;

	return *this;
}

FormUrlEncodedRequest& FormUrlEncodedRequest::AddKeyValue(const char* key, const CStringW &value)
{
	return AddKeyValue(key, EncodeToUTF8(value));
}

FormUrlEncodedRequest& FormUrlEncodedRequest::AddKeyValue(const char* key, const wchar_t* value)
{
	return AddKeyValue(key, (CStringW)value);
}

FormUrlEncodedRequest& FormUrlEncodedRequest::AddKeyValue(const char* key, int value)
{
	char buf[64];
	_itoa_s(value, buf, 10);

	return AddKeyValue(key, buf);
}

CString FormUrlEncodedRequest::GetHead() const
{
	TCHAR szBuf[255];

	_stprintf_s
		( szBuf
		, _T("Content-type: application/x-www-form-urlencoded\r\n")
		  _T("Content-length: %u\r\n")
	    , m_content.GetLength()
		);

    return szBuf;
}

const CStringA &FormUrlEncodedRequest::GetBody() const
{
    return m_content;
}

HRESULT FormUrlEncodedRequest::GetBody(CComVariant &vtBody) const
{
	LPSAFEARRAY psa = SafeArrayCreateVector(VT_UI1, 0, m_content.GetLength());
	if (!psa) return E_OUTOFMEMORY;

	HRESULT hr;
	void* pData = NULL;
	if (FAILED(hr = SafeArrayAccessData(psa, &pData)))
		return hr;

	CopyMemory(pData, (LPCSTR)m_content, m_content.GetLength());
	hr = SafeArrayUnaccessData(psa);

	vtBody.vt = VT_ARRAY | VT_UI1;
	vtBody.parray = psa;

	return hr;
}
